package com.yuyang.wifi.views.recyclerview;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;

import com.yuyang.wifi.R;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;


/**
 * 指定高度的RecyclerView
 * Created by wislie on 2017/12/7.
 */

public class SpecifiedRecyclerView extends RecyclerView {

    private int max_height = 0;

    public SpecifiedRecyclerView(Context context) {
        this(context, null);
    }

    public SpecifiedRecyclerView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SpecifiedRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.SpecifiedRecyclerView);
        max_height = typedArray.getDimensionPixelSize(R.styleable.SpecifiedRecyclerView_recycler_height, max_height);
        typedArray.recycle();
    }

    @Override
    protected void onMeasure(int widthSpec, int heightSpec) {
        int heightMode = MeasureSpec.getMode(heightSpec);
        int heightSize = MeasureSpec.getSize(heightSpec);

        if (heightMode == MeasureSpec.EXACTLY) {
            heightSize = heightSize <= max_height ? heightSize
                    : max_height;
        }

        if (heightMode == MeasureSpec.UNSPECIFIED) {
            heightSize = heightSize <= max_height ? heightSize
                    : max_height;
        }
        if (heightMode == MeasureSpec.AT_MOST) {
            heightSize = heightSize <= max_height ? heightSize
                    : max_height;
        }
        int maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize,
                heightMode);
        super.onMeasure(widthSpec, maxHeightMeasureSpec);
    }
}
